package com.gc.ykqx.ui.fragment;


import android.Manifest;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gc.ykqx.R;
import com.gc.ykqx.service.entity.Fore;
import com.gc.ykqx.service.entity.Fylz;
import com.gc.ykqx.service.entity.LatestWea;
import com.gc.ykqx.service.entity.Warn;
import com.gc.ykqx.service.presenter.ForePresenter;
import com.gc.ykqx.service.presenter.FylzPresenter;
import com.gc.ykqx.service.presenter.LatestWeaPresenter;
import com.gc.ykqx.service.presenter.WarnPresenter;
import com.gc.ykqx.service.util.Constant;
import com.gc.ykqx.service.util.DateUtil;
import com.gc.ykqx.service.util.LocationManager;
import com.gc.ykqx.service.util.ParseUtil;
import com.gc.ykqx.service.util.PermissionUtils;
import com.gc.ykqx.service.view.ForeView;
import com.gc.ykqx.service.view.FylzView;
import com.gc.ykqx.service.view.LatestWeaView;
import com.gc.ykqx.service.view.WarnView;
import com.gc.ykqx.ui.custom.LazyFragment;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends LazyFragment implements SwipeRefreshLayout.OnRefreshListener, LocationManager.LocationListener {

    private static final String TAG = "HomeFragment";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.fore_title)
    TextView foreTitle;
    @BindView(R.id.fore_content)
    TextView foreContent;
    @BindView(R.id.warn_content)
    TextView warnContent;
    @BindView(R.id.tem_value)
    TextView temValue;
    @BindView(R.id.pre_value)
    TextView preValue;
    @BindView(R.id.wind_value)
    TextView windValue;
    @BindView(R.id.vis_value)
    TextView visValue;
    @BindView(R.id.rel_value)
    TextView relValue;
    @BindView(R.id.prs_value)
    TextView prsValue;
    @BindView(R.id.fylz_value)
    TextView fylzValue;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.factor_time)
    TextView factorTime;
    @BindView(R.id.loc_layout)
    LinearLayout locLayout;
    @BindView(R.id.yk_layout)
    LinearLayout ykLayout;
    @BindView(R.id.fore_layout)
    RelativeLayout foreLayout;
    Unbinder unbinder;
    @BindView(R.id.main_layout)
    RelativeLayout mainLayout;
    @BindView(R.id.yj_img)
    ImageView yjImg;

    private Context mContext;
    private boolean isPrepared;
    private boolean isLoaded;
    private LocationManager locationManager;//获取定位信息
    private WarnPresenter warnPresenter;//预警信息
    private LatestWeaPresenter latestWeaPresenter;//最新天气
    private FylzPresenter fylzPresenter;//负氧离子
    private ForePresenter forePresenter;//预报
    private String mForeType;
    private String staId;

    public HomeFragment() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (locationManager != null) {
            locationManager.destroy();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        isPrepared = true;
        lazyLoad();
        return view;
    }

    private void init() {
        mContext = getContext();
        warnPresenter = new WarnPresenter(mContext);
        warnPresenter.onCreate();
        warnPresenter.attachView(warnView);
        latestWeaPresenter = new LatestWeaPresenter(mContext);
        latestWeaPresenter.onCreate();
        latestWeaPresenter.attachView(latestWeaView);
        fylzPresenter = new FylzPresenter(mContext);
        fylzPresenter.onCreate();
        fylzPresenter.attachView(fylzView);
        forePresenter = new ForePresenter(mContext);
        forePresenter.onCreate();
        forePresenter.attachView(foreView);
        locationManager = new LocationManager(this);
        refreshLayout.setOnRefreshListener(HomeFragment.this);
    }

    private WarnView warnView = new WarnView() {
        @Override
        public void onSuccess(Warn warn) {
            if (warn.getReturnCode() == Constant.Response.SUCCESS_CODE) {
                Log.e(TAG, "预警信息->: " + warn.toString());
                setWarn(warn);
            }
        }

        @Override
        public void onError(String result) {

        }
    };

    private LatestWeaView latestWeaView = new LatestWeaView() {
        @Override
        public void onSuccess(LatestWea latestWea) {
            if (latestWea.getReturnCode() == Constant.Response.SUCCESS_CODE) {
                Log.e(TAG, "定位站点天气->: " + latestWea.toString());
                setLatestWea(latestWea);
            }
        }

        @Override
        public void onError(String result) {

        }
    };

    private FylzView fylzView = new FylzView() {
        @Override
        public void onSuccess(Fylz fylz) {
            Log.e(TAG, "负氧离子->: " + fylz.toString());
            setFylz(fylz);
        }

        @Override
        public void onError(String result) {

        }
    };

    private ForeView foreView = new ForeView() {
        @Override
        public void onSuccess(Fore fore, String foreType) {
            if (refreshLayout != null && refreshLayout.isRefreshing()) {
                refreshLayout.setRefreshing(false);
            }
            if (fore.getReturnCode() == Constant.Response.SUCCESS_CODE) {
                Log.e(TAG, "预报信息->: " + fore.toString());
                setFore(fore, foreType);
            }
        }

        @Override
        public void onError(String result) {

        }
    };

    private void setWarn(Warn warn) {
        try {
            if (warn != null && warn.getDS() != null && warn.getDS().size() > 0) {
                for (Warn.DSBean ds : warn.getDS()) {
                    if (ds.getUnitname().equals(Constant.YK_UNIT_NAME)) {
                        String name = ds.getYjch();
                        int[] result = ParseUtil.getYjImg(name);
                        yjImg.setImageResource(result[0]);
                        warnContent.setText(name);
                        warnContent.setTextColor(getResources().getColor(result[1]));
                    }
                }

            }
        } catch (Exception e) {
            Log.e(TAG, "setWarn: " + e.getMessage());
        }
    }

    private void setLatestWea(LatestWea latestWea) {
        String pre = "无降水";
        try {
            for (LatestWea.DSBean bean : latestWea.getDS()) {
                if (bean.getStationId().equals(Constant.YK_STA_ID)) {
                    visValue.setText(bean.getVisibility() + "km");
                    relValue.setText(bean.getRelHumidity() + "%");
                    prsValue.setText(bean.getStationPress() + "hPa");
                }
                if (bean.getStationId().equals(staId)) {
                    temValue.setText(bean.getDryBulTemp() + "℃");
                    windValue.setText(bean.getWindVelocity() + "m/s");
                    if (bean.getPrecipitation() != null) {
                        double v = Double.parseDouble(bean.getPrecipitation());
                        if (v > 0 && v < 0.1) {
                            pre = "微量";
                        } else if (v >= 0.1) {
                            pre = bean.getPrecipitation() + "mm";
                        }
                    }
                    preValue.setText(pre);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "setWarn: " + e.getMessage());
        }
    }

    private void setFylz(Fylz fylz) {
        try {
            String migrationRate04 = fylz.getMigrationRate04();
            fylzValue.setText(migrationRate04+"个/cm³");
        } catch (Exception e) {
            Log.e(TAG, "setWarn: " + e.getMessage());
        }
    }

    private void setFore(Fore fore, String foreType) {
        try {
            Fore.DSBean bean = fore.getDS().get(0);
            if (mForeType.equals(Constant.Fore.SHORT_DATE)) {
                foreTitle.setText("短期预报");
            } else {
                foreTitle.setText("未来三小时预报");
            }
            if (mForeType.equals(foreType)) {//// TODO: 2017/10/13  用于防止 预报页面刷新数据 首页预报也改变 但可能会报异常
                foreContent.setText(ParseUtil.parseFore(bean.getFILE_Text(), mForeType));
            }
        } catch (Exception e) {
            Log.e(TAG, "setWarn: " + e.getMessage());
        }

    }

    private void checkPermission() {
        PermissionUtils.requestPermissionsResult(this, 2, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE},
                new PermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        locationManager.setmLocationOption();
                    }

                    @Override
                    public void onPermissionDenied() {
                        PermissionUtils.showTipsDialog(getContext());
                    }
                });
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || isLoaded) {
            return;
        }
        initData();
        isLoaded = true;
    }

    @Override
    public void onRefresh() {
        initData();
    }

    private void initData() {
        factorTime.setText(DateUtil.getShowTime(DateUtil.getNewTime(Constant.Time.TIME_MIN), Constant.Time.TIME_MIN));
        // mainLayout.setVisibility(View.GONE);
        mForeType = DateUtil.getForeType();
        locationManager.setmLocationOption();
        //  checkPermission();
    }

    @Override
    public void onLocationSuccess(String address) {
        tvTitle.setText(address);
        staId = ParseUtil.getSiteIdAndTownByTownship(address);
        warnPresenter.getWarn();
        latestWeaPresenter.getLatestWea(Constant.YK_STA_ID + "," + staId);
        fylzPresenter.getFylz();
        forePresenter.getFore(mForeType);
    }
}
